package im.agents.monitor;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import jade.core.AID;
import jade.core.behaviours.Behaviour;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import im.agents.IMAgent;
import im.agents.INodeMonitor;
import im.domain.MonitorData;
import im.domain.SLA;

public class NodeMonitor extends IMAgent implements INodeMonitor{

	private static final long TICK = 1000;
	private Vector<SLA> monitored = new Vector<SLA>();
	private Map<String,MonitorData> monitorData = new HashMap<String,MonitorData>();
	private Map<String,Behaviour> tickerBehaviours = new HashMap<String,Behaviour>();
	@Override
	public ServiceDescription getServiceDescription() {
		ServiceDescription s = new ServiceDescription ();
		s.setName("monitor");
		s.setType("monitor");
		return s;
	}
	
	/* (non-Javadoc)
	 * @see im.agents.monitor.INodeMonitor#startSniffing(im.domain.SLA, jade.core.AID)
	 */
	public void startSniffing(SLA sla, AID sc){
		
		if(isBeingMonitored(sla))return;
		
		monitored.add(sla);
		Behaviour ticker =new SendMonitorDataOnTick(this,TICK,sc,sla); 
		tickerBehaviours.put(sla.toString(),ticker );
		monitorData.put(sla.toString(), new MonitorData());
		addBehaviour(ticker);
	}
	/* (non-Javadoc)
	 * @see im.agents.monitor.INodeMonitor#stopSniffing(im.domain.SLA)
	 */
	public void stopSniffing(SLA sla){
		if(!isBeingMonitored(sla))return;
		Behaviour ticker = tickerBehaviours.remove(sla.toString());
		monitorData.remove(sla.toString());
		removeBehaviour(ticker);
		monitored.remove(sla);
	}
	/* (non-Javadoc)
	 * @see im.agents.monitor.INodeMonitor#isBeingMonitored(im.domain.SLA)
	 */
	public boolean isBeingMonitored(SLA sla){
		return monitored.contains(sla)&&
			monitorData.containsKey(sla.toString())&&
			tickerBehaviours.containsKey(sla.toString());
	}
	
	public void setup(){
		super.setup();
		this.doWait(1000);
		addBehaviour(new ManageMonitoringRequests(this));
		addBehaviour(new RefreshMonitorData(this,3000));
	}
	public void takeDown(){
		super.takeDown();
		
	}

	/* (non-Javadoc)
	 * @see im.agents.monitor.INodeMonitor#getMonitored()
	 */
	public Vector<SLA> getMonitored() {
		return monitored;
	}

	public void setMonitored(Vector<SLA> monitored) {
		this.monitored = monitored;
	}

	/* (non-Javadoc)
	 * @see im.agents.monitor.INodeMonitor#getMonitorData()
	 */
	public Map<String, MonitorData> getMonitorData() {
		return monitorData;
	}

	public void setMonitorData(Map<String, MonitorData> monitorData) {
		this.monitorData = monitorData;
	}

	public Map<String, Behaviour> getTickerBehaviours() {
		return tickerBehaviours;
	}

	public void setTickerBehaviours(Map<String, Behaviour> tickerBehaviours) {
		this.tickerBehaviours = tickerBehaviours;
	}
}
